/**
 * TermNode.java 1.0 2007-6-21 下午09:46:12,创建 by yangfan
 */


package org.in4j.compiler.sandbox.calcuator;

import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <TERM> ::= <NUM> + <EXPR> | <NUM> - <EXPR>
 * @author yangfan
 * @version 1.0 2007-6-21 下午09:46:12,创建
 */
public class TermNode implements Node
{
	@SuppressWarnings("unused")
	private static final Log log = LogFactory.getLog(TermNode.class);

	private int value;
	private String operator;
	private Node left;
	private Node right;
	private TermNode parent;

	public void execute()
	{
//		left.execute();
		final int operand = left.getValue();
		System.out.println("currentNode==>" + this + ",operand==>" + operand);

		right.execute();
		final int nextVal = right.getValue();
		if(operator.equals("+"))
		{
			value = operand + nextVal;
		}
		else if(operator.equals("-"))
		{
			value = operand - nextVal;
		}
		else
		{
			throw new RuntimeException("error!");
		}
		if(parent != null)
		{
			parent.execute();
			value = parent.getValue();
		}
	}

	public void parse(Context context)
	{
		context.nextToken();
		String token = context.currentToken();
		context.back();
		if(isDigit(token))
		{
			left = new NumNode();
			left.parse(context);
		}

		context.nextToken();
		token = context.currentToken();

		if(!token.equals("+") && !token.equals("-"))
			throw new RuntimeException("compiler error: error token '" + token + "',expected '+' or '-'");
		this.operator = token;

		right = new NumNode();
		right.parse(context);
		log.debug("add right node:" + right);
		if(context.hasNextToken())
		{
			parent = new TermNode();
			parent.parse(context);
			parent.setChild(this);
			log.debug("add parent node:" + parent);
		}
	}

	private void setChild(TermNode node)
	{
		this.left = node;
	}

	private boolean isDigit(String nextToken)
	{
		return Pattern.matches("\\d+", nextToken);
	}

	public int getValue()
	{
		return value;
	}

	@Override
	public String toString()
	{
		return "<TermNode," + operator + ">";
	}
}
